package com.kfm.web.controller.order;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kfm.common.domain.entity.Member;
import com.kfm.common.domain.entity.OrderDetails;
import com.kfm.common.domain.entity.Orders;
import com.kfm.common.domain.response.Result;
import com.kfm.common.exception.ServerException;
import com.kfm.common.util.JwtUtils;
import com.kfm.order.service.AlipayService;
import com.kfm.order.service.OrdersService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrdersService service;

    @Resource
    private AlipayService alipayService;

    /**
     * 下单
     *
     * @return
     */
    @PostMapping("/place")
    public byte[] order(@RequestBody String map, HttpServletRequest request) throws Exception {
        // 下单的时候需要提供 应付金额，实付金额，所有商品编号，数量，单价 前端构建的时候 应该
        String token = request.getHeader("token");
        if (token == null) {
            throw new ServerException("请先登录", 401);
        }
        // 登录用户信息
        Member member = JSONUtil.toBean(JwtUtils.getSubject(token), Member.class);
        JSONObject params = JSONUtil.parseObj(map);
        JSONArray products = params.getJSONArray("products");
        List<OrderDetails> list = products.stream()
                .map(obj -> {
                    JSONObject current = (JSONObject) obj;
                    OrderDetails details = new OrderDetails();
                    details.setProductId((Integer) current.getJSONObject("product").get("productId"));
                    details.setQuantity((Integer) current.get("quantity"));
                    details.setMemberId(member.getId());
                    details.setUnitPrice((BigDecimal) current.getJSONObject("product").get("price"));
                    return details;
                })
                .toList();
        Orders orders = new Orders();
        orders.setMemberId(member.getId());
        orders.setTotalAmount(params.getDouble("totalAmount"));
        orders.setMemberId(member.getId());
        orders.setStatus("待付款");
        // 现在只是创建订单 所以实付金额是 0
        orders.setActualAmount(0.00);
        int i = service.insertSelective(orders, list);
        if (i == 0) {
            throw new ServerException("订单创建失败", 302);
        }
        System.out.println(orders);
        // TODO 调用支付宝沙箱模拟支付
        return alipayService.alipay(orders);
    }

    @RequestMapping("/list")
    public Result list(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            throw new ServerException("请先登录", 401);
        }
        // 登录用户信息
        Member member = JSONUtil.toBean(JwtUtils.getSubject(token), Member.class);
        List<Orders> list = service.selectByMId(member.getId());
        return list == null ? Result.failure("查询失败") : Result.success("查询成功", list);
    }

    @RequestMapping("/getOne/{id}")
    public Result getOne(@PathVariable("id") String id) {
        Orders orders = service.selectByPrimaryKey(id);
        return orders == null ? Result.failure("查询失败") : Result.success("查询成功", orders);
    }

    @RequestMapping("/delete/{id}")
    public Result remove(@PathVariable("id") String id) {
        int i = service.deleteByPrimaryKey(id);
        return i == 0 ? Result.failure("删除失败") : Result.success("删除成功");
    }

    @RequestMapping("/cancel/{id}")
    public Result cancel(@PathVariable("id") String id) {
        Orders orders = service.selectByPrimaryKey(id);
        orders.setStatus("取消");
        int i = service.updateByPrimaryKey(orders);
        return i == 0 ? Result.failure("取消失败") : Result.success("取消成功");
    }
}
